package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.geoaimavlink_android.R
import com.example.geoaimavlink_android.activity.view.FilePickerFullScreen
import com.geoai.mavlink.geoainet.base.mavlinkcore.engine.GEOAIError
import com.geoai.mavlink.geoainet.mission.enums.MissionFinishAction
import com.geoai.mavlink.geoainet.mission.enums.MissionFlyToWaylineMode
import com.geoai.mavlink.geoainet.mission.enums.MissionState
import com.geoai.mavlink.geoainet.mission.enums.MissionUploadState
import com.geoai.mavlink.geoainet.mission.enums.OrbitYawBehaviour
import com.geoai.mavlink.geoainet.mission.factory.MissionItemBuilder
import com.geoai.mavlink.geoainet.mission.factory.MissionItemBuilder.Waypoint
import com.geoai.mavlink.geoainet.mission.factory.action.ActionAircraftStay
import com.geoai.mavlink.geoainet.mission.factory.action.ActionRoi
import com.geoai.mavlink.geoainet.mission.factory.action.BaseAction
import com.geoai.mavlink.geoainet.mission.interfaces.IMissionStateListener
import com.geoai.mavlink.geoainet.mission.interfaces.IMissionUploadListener
import com.geoai.mavlink.geoainet.mission.interfaces.IWpmlCoverListener
import com.geoai.mavlink.util.FileUtils
import com.github.gzuliyujiang.filepicker.ExplorerConfig
import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode
import kotlinx.android.synthetic.main.frag_mission.btn_mission_continue
import kotlinx.android.synthetic.main.frag_mission.btn_mission_p2p
import kotlinx.android.synthetic.main.frag_mission.btn_mission_pause
import kotlinx.android.synthetic.main.frag_mission.btn_mission_start
import kotlinx.android.synthetic.main.frag_mission.btn_mission_stop
import kotlinx.android.synthetic.main.frag_mission.btn_mission_upload
import kotlinx.android.synthetic.main.frag_mission.btn_mission_wpml
import kotlinx.android.synthetic.main.frag_mission.tv_mission_state_info
import kotlinx.android.synthetic.main.frag_mission.tv_mission_upload_index
import kotlinx.android.synthetic.main.frag_mission.tv_mission_upload_state
import java.lang.StringBuilder

class MissionFragment : BaseFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_mission, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initSDK()
    }

    private fun initView() {
        btn_mission_upload.setOnClickListener {
            uploadMission(buildMission3())
        }
        btn_mission_start.setOnClickListener {
            getProduct()?.missionManager?.startMission { showToast(it?.description ?: "success") }
        }
        btn_mission_pause.setOnClickListener {
            getProduct()?.missionManager?.pauseMission { showToast(it?.description ?: "success") }
        }
        btn_mission_continue.setOnClickListener {
            getProduct()?.missionManager?.continueMission { showToast(it?.description ?: "success") }
        }
        btn_mission_stop.setOnClickListener {
            getProduct()?.missionManager?.stopMission { showToast(it?.description ?: "success") }
        }
        btn_mission_p2p.setOnClickListener {
//            getProduct()?.missionManager?.sendOrbitCommand(23.1637539, 113.4398588, 10.0f, 5.0f, 1.0f, OrbitYawBehaviour.ORBIT_YAW_BEHAVIOUR_HOLD_FRONT_TANGENT_TO_CIRCLE, null)
//            getProduct()?.missionManager?.sendPositionCommand(23.1637539, 113.4398588, 10.0f, 1.0f, null)
        }
        btn_mission_wpml.setOnClickListener {
            FilePickerFullScreen(requireActivity()).apply {
                setExplorerConfig(ExplorerConfig(context).apply {
                    rootDir = context.getExternalFilesDir(null)
                    isLoadAsync = false
                    explorerMode = ExplorerMode.FILE
                    setOnFilePickedListener {
                        val wpml = FileUtils.readFileAsString(it.path)
                        getProduct()?.missionManager?.coverWPMLMission(wpml, object : IWpmlCoverListener{
                            override fun onFailure(geoaiError: GEOAIError?) {
                                showToast(geoaiError?.description?:"unknown error")
                            }

                            override fun onSuccess(builder: MissionItemBuilder.Builder?) {
                                builder?.let {missionBuilder ->
                                    uploadMission(missionBuilder.build())
                                }
                            }
                        })
                    }
                })
                show()
            }
        }
    }

    private fun uploadMission(buildMission3: MissionItemBuilder) {
        getProduct()?.missionManager?.uploadMission(buildMission3, object : IMissionUploadListener{
            override fun onMissionUploadState(state: MissionUploadState?) {
                tv_mission_upload_state?.text = state?.name?:"unknown"
            }

            override fun onUploadProgress(index: Int, progress: Int) {
                tv_mission_upload_index?.text = "index: $index --- progress:$progress"
            }

            override fun onMissionUploadResult(isSuccess: Boolean, error: GEOAIError?) {
                showToast("mission upload: $isSuccess" + error?.description)
            }
        })
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) {
            if (it.isAircraftConnected) {
                getProduct()?.missionManager?.setMissionStateListener(object :
                    IMissionStateListener {
                    override fun onMissionState(
                        state: MissionState?,
                        totalWaypoint: Int,
                        currentWaypoint: Int,
                        currentAction: Int,
                        isReadyToMission: Boolean
                    ) {
                        val sb = StringBuilder()
                        sb.append("TS: ${System.currentTimeMillis()}").append("\r\n")
                        sb.append("MissionState: ${state?.name ?: "unknown"}").append("\r\n")
                        sb.append("TotalWaypoint: $totalWaypoint").append("\r\n")
                        sb.append("CurrentWaypoint: $currentWaypoint").append("\r\n")
                        sb.append("CurrentAction: $currentAction").append("\r\n")
                        tv_mission_state_info?.text = sb.toString()
                    }

                    override fun onMissionStart() {
                        showToast("mission start.")
                    }

                    override fun onMissionFinish() {
                        showToast("mission finish.")
                    }
                })
            }
        }
    }

    override fun onDestroyView() {
        msdkInfoVm.msdkInfo.removeObservers(viewLifecycleOwner)
        getProduct()?.missionManager?.setMissionStateListener(null)
        super.onDestroyView()
    }

    //    ----------------------任务构建------------------------
    private fun buildMission1(): MissionItemBuilder {
        //用来测试Mission组件中的属性
        val waypoints = mutableListOf<Waypoint>()

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1637539
            it.wayPointLongitude = 113.4398588
            it.wayPointAltitude = 10.0f
        })

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1639707
            it.wayPointLongitude = 113.4397300
            it.wayPointAltitude = 10.0f
        })

        return MissionItemBuilder.Builder()
            .setMissionSpeed(5.0f)
            .setFinishAction(MissionFinishAction.MISSION_FINISH_ACTION_GO_HOME)
            .setWaypointList(waypoints)
            .setFlyToWaylineMode(MissionFlyToWaylineMode.USING_FIRST_WAYPOINT_ALTITUDE)
            .setTakeOffSecurityHeight(20.0f)
            .build()
    }

    private fun buildMission2(): MissionItemBuilder {
        //用来测试Waypoint组件中的属性
        val waypoints = mutableListOf<Waypoint>()

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1637539
            it.wayPointLongitude = 113.4398588
            it.wayPointAltitude = 10.0f
        })

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1639707
            it.wayPointLongitude = 113.4397300
            it.wayPointAltitude = 10.0f
        })

        return MissionItemBuilder.Builder()
            .setMissionSpeed(5.0f)
            .setFinishAction(MissionFinishAction.MISSION_FINISH_ACTION_GO_HOME)
            .setWaypointList(waypoints)
            .build()
    }

    private fun buildMission3(): MissionItemBuilder {
        //用来测试action组件中的属性
        val waypoints = mutableListOf<Waypoint>()

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1637539
            it.wayPointLongitude = 113.4398588
            it.wayPointAltitude = 10.0f

            it.actions = mutableListOf<BaseAction>().also {actions ->
                actions.add(ActionRoi(true, 23.0f, 113.0f, 50.0f))
            }.toTypedArray()
        })

        waypoints.add(Waypoint().also {
            it.wayPointLatitude = 23.1639707
            it.wayPointLongitude = 113.4397300
            it.wayPointAltitude = 10.0f

            it.actions = mutableListOf<BaseAction>().also {actions ->
                actions.add(ActionAircraftStay(5))
            }.toTypedArray()
        })

        return MissionItemBuilder.Builder()
            .setMissionSpeed(2.0f)
            .setFinishAction(MissionFinishAction.MISSION_FINISH_ACTION_GO_HOME)
            .setWaypointList(waypoints)
            .build()
    }
}